<template>
  <!-- 唯一根元素：包裹所有内容 -->
  <view class="page-container">
    <view class="nav-bar"></view>
    <view class="container">
      <!-- 医院下拉框 -->
      <view class="dropdown-container">
        <view class="dropdown-btn" @click="toggleDropdown">
          <view class="btn-text">{{ selectedOption }}</view>
          <uni-icons
            class="dropdown-icon"
            type="down"
            size="24"
            :rotate="isDropdownOpen ? 180 : 0"></uni-icons>
        </view>
        <view class="dropdown-menu" v-show="isDropdownOpen" @click.stop>
          <view
            class="dropdown-item"
            v-for="(item, index) in dropdownOptions"
            :key="index"
            @click="selectDropdownItem(item)">
            {{ item.name }}
          </view>
        </view>
      </view>

      <!-- 标签栏：修复 <uni-grid> 闭合标签 -->
      <view class="tab-view">
        <uni-grid
          :column="4"
          :square="false"
          :showBorder="false"
          :highlight="false">
          <uni-grid-item v-for="(item, index) in tabs" :key="index">
            <view class="grid-item">
              <view
                @click="tabClick(item, index)"
                :class="
                  current === index
                    ? 'grid-item-inner-selected'
                    : 'grid-item-inner'
                ">
                {{ item }}
              </view>
            </view>
          </uni-grid-item>
        </uni-grid>
        <!-- 新增：闭合 uni-grid 标签 -->
      </view>
    </view>

    <!-- 订单列表 -->
    <view
      class="card-view"
      v-for="(item, index) in list"
      @click="navToDetails(item)">
      <view class="title-view">
        <view class="left">
          <view class="title">编号 : {{ item.orderNum || "" }}</view>
        </view>
        <view
          :class="item.status === '已拒绝' ? 'status-type2' : 'status-type1'"
          class="status-text">
          {{ item.status }}
        </view>
      </view>
      <view class="card-body order-card-body">
        <view class="info-row">
          <view class="title">服务项目</view>
          <view class="right value">
            {{
              item.itemInfos && item.itemInfos.length
                ? item.itemInfos.map((e) => e.serviceItem).join("/")
                : "无"
            }}
          </view>
        </view>
        <view class="info-row">
          <view class="title">就诊人</view>
          <view class="right value">{{ item.visitor || "" }}</view>
        </view>
        <view class="info-row">
          <view class="title">联系电话</view>
          <view class="right phone">{{ item.contactPhone || "" }}</view>
          <call-button :phoneNumber="item.contactPhone"></call-button>
        </view>
        <view class="info-row">
          <view class="title">上门地址</view>
          <view class="right value singe-line-ellipsis">
            {{ item.visitorAddress || "" }}
          </view>
        </view>
        <view class="info-row">
          <view class="title">护士名称</view>
          <view class="right value">{{ item.dispatchNurses || "" }}</view>
        </view>
        <view class="op-btn-row">
          <view
            class="btn-type1"
            v-if="['待评估', '待派发'].includes(item.status)">
            拒绝
          </view>
          <view class="btn-type2" v-if="item.status === '待评估'">评估</view>
          <view class="btn-type2" v-if="item.status === '待派发'">派发</view>
          <view class="btn-type3" v-if="item.status === '已拒绝'">已拒绝</view>
        </view>
      </view>
    </view>

    <!-- 无数据提示 -->
    <view v-if="list.length === 0 && !isLoadingOrder" class="no-data-tip">
      {{ selectedHospitalUid ? "暂无对应医院的订单数据" : "暂无订单数据" }}
    </view>

    <!-- 加载状态 -->
    <uni-load-more :status="status" v-if="isShowLoadMore"></uni-load-more>
  </view>
</template>

<script>
import PageInfo from "../../utils/pageutils";
import * as orderInfo from "../../common/api/orderInfo.js";
export default {
  data() {
    return {
      tabs: [
        "全部",
        "待评估",
        "待派发",
        "待出发",
        "待服务",
        "服务中",
        "已评价",
        "已完成",
        "退款/售后",
        "已取消",
      ],
      current: 0,
      form: {},
      pageInfo: new PageInfo(),
      list: [], // 订单列表数据
      status: "more", // 加载更多状态
      orderStatus: "全部", // 当前选中的标签状态

      // 下拉框相关
      isDropdownOpen: false, // 下拉面板显示状态
      selectedOption: "请选择医院", // 下拉选中的医院名称
      selectedHospitalUid: "", // 选中的医院ID（为空时表示未筛选医院）
      dropdownOptions: [], // 医院列表数据（初始为空）
      isLoadingHospital: false, // 医院列表加载中标志

      // 订单列表相关
      isLoadingOrder: false, // 订单列表加载中标志
    };
  },
  computed: {
    // 仅在有订单数据或加载中时显示加载更多组件
    isShowLoadMore() {
      return this.list.length > 0 || this.isLoadingOrder;
    },
  },
  onLoad() {
    // 页面初始加载：立即请求订单列表（不筛选医院）
    this.refreshOrderList();
  },
  onPullDownRefresh() {
    // 下拉刷新：根据是否选中医院，请求对应订单
    this.refreshOrderList();
  },
  onReachBottom() {
    // 上拉加载：有更多数据且不在加载中时触发
    if (this.pageInfo.isNotLoadAll && !this.isLoadingOrder) {
      this.pageInfo.nextPage();
      this.getOrderList();
    }
  },
  methods: {
    // 切换标签：刷新对应状态的订单
    tabClick(item, index) {
      this.current = index;
      this.orderStatus = item;
      this.refreshOrderList();
    },
    // 跳转到详情页
    navToDetails(item) {
      console.log("跳转到详情页", item);
      uni.navigateTo({
        url: "/pages/orderDetails/orderDetails?uid=" + item.uid,
      });
    },
    // 重置并刷新订单列表
    refreshOrderList() {
      this.pageInfo.reset();
      this.list = [];
      this.getOrderList();
    },
    // 核心：请求订单列表接口
    getOrderList() {
      this.isLoadingOrder = true;
      this.status = "loading";

      const param = {
        pageIndex: this.pageInfo.pageIndex,
        pageSize: this.pageInfo.pageSize,
        ...this.form,
      };

      // 若选中医院，则添加医院筛选条件
      if (this.selectedHospitalUid) {
        param.hospitalUid = this.selectedHospitalUid;
      } else {
        const userInfo = uni.getStorageSync("user_info") || "{}";
        const { hospitalUid } = JSON.parse(userInfo) || {};
        param.hospitalUid = hospitalUid;
      }
      console.log("订单请求", param);

      // 标签状态筛选
      if (this.orderStatus === "全部") {
        param.statusList = [
          "待评估",
          "待派发",
          "待出发",
          "待服务",
          "服务中",
          "已评价",
          "已完成",
          "待退款",
          "退款中",
          "已退款",
          "已拒绝",
          "已取消",
        ];
      } else if (this.orderStatus === "退款/售后") {
        param.statusList = ["待退款", "退款中", "已退款", "已拒绝"];
      } else {
        param.status = this.orderStatus;
      }

      // 发起订单列表请求
      orderInfo
        .queryByPage(param)
        .then((result) => {
          this.isLoadingOrder = false;
          const list = result.data.data.rows || [];
          const total = result.data.data.total;

          this.list = [...this.list, ...list];
          this.pageInfo.total = total;
          this.pageInfo.loadedTotal = this.list.length;

          this.status = this.pageInfo.isNotLoadAll ? "more" : "noMore";
          uni.stopPullDownRefresh();
        })
        .catch((error) => {
          this.isLoadingOrder = false;
          console.error("获取订单失败：", error);
          uni.showToast({ title: "获取订单失败", icon: "none" });
          this.status = "more";
          uni.stopPullDownRefresh();
        });
    },

    // 点击下拉框：加载医院列表并显示面板
    toggleDropdown() {
      // 正在加载医院时不重复请求
      if (this.isLoadingHospital) return;

      // 医院列表为空时，先请求医院数据
      if (this.dropdownOptions.length === 0) {
        this.getHospitalList();
        return;
      }

      // 已有医院数据，直接切换面板显示状态
      this.isDropdownOpen = !this.isDropdownOpen;
    },

    // 加载医院列表接口（仅点击下拉框时触发）
    getHospitalList() {
      const userInfo = uni.getStorageSync("user_info") || "{}";
      const { hospitalUid } = JSON.parse(userInfo) || {};

      // 校验用户权限
      if (!hospitalUid) {
        uni.showToast({
          title: "请先登录获取权限",
          icon: "none",
          duration: 2000,
        });
        return;
      }

      this.isLoadingHospital = true;
      uni.showLoading({ title: "加载医院..." });

      // 发起医院列表请求
      orderInfo
        .queryByHospital({ uid: hospitalUid })
        .then((res) => {
          uni.hideLoading();
          this.isLoadingHospital = false;

          const hospitalData = res.data?.data || [];
          if (!Array.isArray(hospitalData)) {
            uni.showToast({ title: "医院数据格式错误", icon: "none" });
            return;
          }

          // 格式化医院数据（仅保留ID和名称）
          this.dropdownOptions = hospitalData
            .map((item) => ({
              uid: item.uid || item.hospitalId, // 兼容不同ID字段
              name: item.hospitalName || item.name || "未知医院",
            }))
            .filter((item) => item.name !== "未知医院"); // 过滤无效数据

          // 加载成功后显示下拉面板
          if (this.dropdownOptions.length > 0) {
            this.isDropdownOpen = true;
          } else {
            uni.showToast({ title: "暂无可用医院", icon: "none" });
          }
        })
        .catch((err) => {
          uni.hideLoading();
          this.isLoadingHospital = false;
          console.error("获取医院列表失败：", err);
          uni.showToast({ title: "加载医院失败", icon: "none" });
        });
    },

    // 选中医院后：请求该医院的订单列表
    selectDropdownItem(item) {
      this.selectedOption = item.name;
      this.selectedHospitalUid = item.uid; // 记录选中的医院ID
      this.isDropdownOpen = false; // 关闭下拉面板
      this.refreshOrderList(); // 刷新订单列表（带医院筛选）
    },
  },
};
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background-color: #f9f9f9;
}

.nav-bar {
  height: 554rpx;
  background: linear-gradient(to bottom, #2eb0d9, #f9f9f9);
}

.container {
  display: flex;
  flex-direction: column;
  margin-top: -500rpx;
  padding-bottom: 20rpx;
}

/* 下拉框样式 */
.dropdown-container {
  position: relative;
  width: calc(100% - 40rpx);
  margin: 0 20rpx 20rpx;
  z-index: 10;
}

.dropdown-btn {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 70rpx;
  padding: 0 20rpx;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 35rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  box-sizing: border-box;
  cursor: pointer;
}

.btn-text {
  font-size: 26rpx;
  color: #333;
}

.dropdown-icon {
  color: #2eb0d9;
  transition: rotate 0.3s ease;
}

.dropdown-menu {
  position: absolute;
  top: 80rpx;
  left: 0;
  width: 100%;
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  z-index: 999;
  overflow: hidden;
}

.dropdown-item {
  padding: 0 20rpx;
  height: 70rpx;
  line-height: 70rpx;
  font-size: 26rpx;
  color: #333;
  border-bottom: 1rpx solid #f5f5f5;

  &:last-child {
    border-bottom: none;
  }

  &:hover {
    background-color: #f0f7fa;
  }
}

/* 标签栏样式 */
.tab-view {
  margin-left: 20rpx;
  margin-right: 20rpx;

  .grid-item {
    width: 100%;
    height: 100%;
    padding: 10rpx;
    box-sizing: border-box;

    .grid-item-inner {
      width: 100%;
      height: 66rpx;
      background: rgba(255, 255, 255, 0.5);
      border-radius: 33rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 26rpx;
      color: rgba(35, 35, 35, 0.8);
    }

    .grid-item-inner-selected {
      width: 100%;
      height: 66rpx;
      border-radius: 33rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 26rpx;
      background: white;
      color: #2eb0d9;
    }
  }
}

/* 订单卡片样式 */
.card-view {
  margin: 24rpx 30rpx 0;
  background: white;
  border-radius: 24rpx;
  padding: 30rpx;
  box-sizing: border-box;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.title-view {
  display: flex;
  align-items: center;

  .left {
    flex: 1;

    .title {
      font-size: 28rpx;
      color: #000;
      font-weight: bold;
    }
  }

  .status-text {
    font-size: 30rpx;
  }

  .status-type1 {
    color: #f5803d;
  }

  .status-type2 {
    color: rgba(35, 35, 35, 0.4);
  }
}

.order-card-body {
  margin-top: 10rpx;

  .info-row {
    display: flex;
    min-height: 60rpx;
    align-items: center;
    margin-bottom: 12rpx;

    .title {
      width: 150rpx;
      color: rgba(35, 35, 35, 0.7);
      font-size: 26rpx;
    }

    .right {
      flex: 1;
    }

    .value {
      font-size: 26rpx;
      color: #232323;
    }

    .phone {
      color: #2eb0d9;
      font-size: 30rpx;
    }

    .singe-line-ellipsis {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .op-btn-row {
    display: flex;
    justify-content: flex-end;
    margin-top: 10rpx;

    .btn-type1,
    .btn-type2,
    .btn-type3 {
      width: 150rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 60rpx;
      margin-left: 10rpx;
      font-size: 26rpx;
    }

    .btn-type1 {
      border: 1rpx solid #2eb0d9;
      color: #2eb0d9;
    }

    .btn-type2 {
      background: #2eb0d9;
      color: white;
    }

    .btn-type3 {
      background: #f0f0f0;
      color: #c5c5c5;
    }
  }
}

/* 无数据提示 */
.no-data-tip {
  margin: 100rpx 0;
  text-align: center;
  font-size: 26rpx;
  color: #999;
}

/* 加载更多 */
.uni-load-more {
  margin: 40rpx 0;
  text-align: center;
}
</style>
